package login

import (
	"fmt"
	"io"
	"io/ioutil"
	"log"
	"net/http"
	"net/http/cookiejar"
	"net/url"
	"os"
	"strings"
)

const (
	loginURL    = "https://stu.5zk.com.cn/zk8exam/check_login.php"
	myCookieURL = "https://stu.5zk.com.cn/zk8exam/mycourse.php"
	cookieFile  = "cookies.txt" // 保存 cookies 的文件
)

type LoginUser struct {
	AdminName     string `json:"admin_name"`
	AdminPassword string `json:"admin_password"`
	SorT          string `json:"s_or_t"`
}

func (user *LoginUser) toValues() url.Values {
	return url.Values{
		"admin_name":     {user.AdminName},
		"admin_password": {user.AdminPassword},
		"s_or_t":         {user.SorT},
	}
}

// Login 登录
func Login(client *http.Client, user *LoginUser) error {
	//form := url.Values{}
	//form.Add("admin_name", user.AdminName)
	//form.Add("admin_password", user.AdminPassword)
	//form.Add("s_or_t", user.SorT)

	form := user.toValues()

	req, err := http.NewRequest("POST", loginURL, strings.NewReader(form.Encode()))
	if err != nil {
		return fmt.Errorf("failed to create request: %v", err)
	}

	req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
	req.Header.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/135.0.0.0 Safari/537.36")

	resp, err := client.Do(req)
	if err != nil {
		return fmt.Errorf("failed to send request: %v", err)
	}
	defer resp.Body.Close()

	if resp.StatusCode != http.StatusOK {
		return fmt.Errorf("login failed with status: %d", resp.StatusCode)
	}

	body, err := io.ReadAll(resp.Body)
	if err != nil {
		return fmt.Errorf("failed to read response body: %v", err)
	}
	fmt.Println("Status Code:", resp.Status)
	fmt.Println("Response Body:", string(body))
	if strings.Contains(string(body), "用户名不存在") {
		return fmt.Errorf("用户名不存在")
	}
	if strings.Contains(string(body), "用户名或密码错误") {
		return fmt.Errorf("用户名或密码错误")
	}
	return nil
}

// CookiesExist 判断cookies文件是否存在
func CookiesExist() bool {
	_, err := os.Stat(cookieFile)
	return !os.IsNotExist(err)
}

// LoadCookies 加载cookies
func LoadCookies() *cookiejar.Jar {
	jar, _ := cookiejar.New(nil)
	if CookiesExist() {
		file, err := os.Open(cookieFile)
		if err != nil {
			panic(fmt.Sprintf("读取cookie文件失败", err))
		}
		defer file.Close()

		var cookies []*http.Cookie
		for {
			var name, value string
			_, err := fmt.Fscanf(file, "%s %s\n", &name, &value)
			if err != nil {
				break
			}
			cookies = append(cookies, &http.Cookie{Name: name, Value: value})
		}

		logUrl, _ := url.Parse(loginURL)
		jar.SetCookies(logUrl, cookies)

	}
	return jar
}

// SaveCookies 保存cookies
func SaveCookies(client *http.Client) error {
	file, err := os.Create(cookieFile)
	if err != nil {
		return fmt.Errorf("failed to create cookie file: %v", err)
	}
	defer file.Close()

	logUrl, _ := url.Parse(loginURL)
	cookies := client.Jar.Cookies(logUrl)
	for _, cookie := range cookies {
		_, err := fmt.Fprintf(file, "%s %s\n", cookie.Name, cookie.Value)
		if err != nil {
			return fmt.Errorf("failed to write cookie to file: %v", err)
		}
	}
	return nil
}

func CheckLogin(client *http.Client) bool {

	if !CookiesExist() {
		return false
	}
	req, err := http.NewRequest("GET", myCookieURL, nil)
	resp, err := client.Do(req)
	if err != nil {
		return false
	}
	defer resp.Body.Close() // 确保关闭响应体
	body, err := io.ReadAll(resp.Body)
	if err != nil {
		return false
	}
	if strings.Contains(string(body), "<script>top.location.href='login.php';</script>") {
		return false
	}
	return true
}

func GetPHPSESSID() (string, error) {
	content, err := ioutil.ReadFile("cookies.txt")
	if err != nil {
		log.Printf("Err: Failed to read cookies.txt")
		return "", fmt.Errorf("failed to read cookies.txt: %v", err)
	}

	// 将内容转换为字符串
	fileContent := string(content)
	// 处理内容
	parts := strings.Split(fileContent, " ")
	if len(parts) < 2 {
		log.Printf("Err: Invalid cookies format")
		return "", fmt.Errorf("invalid cookies format")
	}

	// 获取 PHPSESSID 值
	phpsessid := strings.TrimSpace(parts[1])

	return phpsessid, nil
}
